# -*- coding: utf-8 -*-
import logging
import json

from api.lottery import ORDER_HANDLER, ORDER_LOGIC, LOTTERY_TYPE
from async.async_job import stats_recharge
from common.lottery.cyclical.abstract.order import BatchOrderPayer, check_buy_list_activity_type, check_buy_list_bet_type, check_user_is_virtual
from common.lottery.handler import smart_track_handler

_LOGGER = logging.getLogger('worker')


def pay_after_recharge(pay, new_version=False):
    # 新版本关闭老的充值活动
    if not new_version:
        stats_recharge.delay(pay.id)
    extend = json.loads(pay.extend or '{}')
    buy_list = extend.get('buy_list', [])
    if not buy_list:
        return
    activity_type = check_buy_list_activity_type(buy_list)
    bet_type_list = check_buy_list_bet_type(buy_list)
    handler = ORDER_HANDLER[activity_type]
    logic = ORDER_LOGIC[activity_type]
    smart_track = extend.get('smart_track')
    if smart_track:
        if activity_type == LOTTERY_TYPE.BJ_PK10:
            # bj_pk10智能追号客户端有bug，此处屏蔽掉
            return
        for item in buy_list:
            handler.check_order_params(item)
            smart_track_handler(pay.user_id, activity_type, item, smart_track, logic)
        return {}

    coupon = extend.get('coupon', None)
    is_track = False
    activity_type = check_buy_list_activity_type(buy_list)
    for item in buy_list:
        handler = ORDER_HANDLER.get(activity_type)
        logic = ORDER_LOGIC[activity_type]
        handler.check_order_params(item)
        item['price'] = logic.calc_total_price(
            item['bet_type'], item['number'], item['times'], item['unit'])
        if item.get('term_count') != 1:
            is_track = True
    if is_track or not coupon:
        for buy_info in buy_list:
            handler = ORDER_HANDLER.get(activity_type)
            try:
                handler.create_order(pay.user_id, buy_info)
            except Exception as e:
                _LOGGER.exception('create order fail for pay [%s], msg: [%s]',
                                  pay.id, e)
    else:
        try:
            is_virtual = check_user_is_virtual(pay.user_id)
            for bet_type in bet_type_list:
                order_payer = BatchOrderPayer(activity_type, pay.user_id, coupon, buy_list, bet_type, is_virtual)
            order_payer.batch_pay()
        except Exception as e:
            _LOGGER.exception('create batch order fail for pay [%s], %s', pay.id, e)
